﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.IO;

namespace StudioLive
{

    public partial class Form1 : Form
    {
        // Create thread for server to run on
        System.Threading.Thread serverThread = null;


        public Form1()
        {
            InitializeComponent();
            logText("Starting StudioLive...");
            logText("Loading settings...");
            loadSettings();
            logText("Loading script...");
            loadScript();
            logText("Done");
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            if (vars.serverState == false)
            {
                logText(startServer());
            }
            else
            {
                logText("The server is already running.");
            }
        }

        private void logText(string text)
        {
            logTB.Text = DateTime.Now + "  -  " + text + "\r\n" + logTB.Text;
        }

        // Settings
        public void loadSettings()
        {
            try
            {
                // Read the settings file
                string line;
                System.IO.StreamReader file = new System.IO.StreamReader(Directory.GetParent(Application.ExecutablePath).ToString() + "/settings.txt");
                while ((line = file.ReadLine()) != null)
                {
                    String[] settings = { "ip", "port", "logoSource", "backgroundSource", "scriptSource"};
                    foreach (string setting in settings)
                    {
                        String settingName = setting + ": ";
                        if (line.StartsWith(settingName))
                        {
                            String settingValue = line.Replace(settingName, "");
                            logText(setting + " - " + settingValue);

                            // Loop through settings options and perform actions
                            switch (setting)
                            {
                                case "ip":
                                    {
                                        vars.ip = settingValue;
                                        break;
                                    };
                                case "port":
                                    {
                                        vars.port = settingValue;
                                        break;
                                    }
                                case "logoSource":
                                    {
                                        vars.logoSource = settingValue;
                                        show.logoPlayer1.ImageLocation = vars.logoSource;
                                        break;
                                    }
                                case "backgroundSource":
                                    {
                                        vars.backgroundSource = settingValue;                                 
                                        break;
                                    }
                                case "scriptSource":
                                    {
                                        vars.scriptSource = "/" + settingValue;
                                        break;
                                    }
                            }

                        }
                    }
                }
                file.Close();
                logText("Settings loaded...");
            }catch (Exception ex){
                logText(ex.ToString());
            }
        }

        // Server
        public string startServer()
        {
            serverThread = new Thread(serverRunner);
            serverThread.Start();

            vars.serverState = true;
            return "Server started";
        }
        public string stopServer()
        {
            try
            {
                listener.Stop();
                serverThread.Abort();

                vars.serverState = false;
                return "Server stopped.";
            }
            catch
            {
                return "Couldn't stop server.";
            }
        }
        HttpListener listener = null;
        public void serverRunner()
        {
            try
            {
                try
                {
                    listener = new HttpListener();
                    listener.Prefixes.Add("http://localhost:" + vars.port + "/");
                    listener.Prefixes.Add("http://" + vars.ip + ":" + vars.port + "/");
                    listener.Start();

                    while (true)
                    {
                        saveLogText("Waiting for input...");

                        // Listen to requests
                        HttpListenerContext context = listener.GetContext();
                        if (context.Request.Url.ToString().Contains("favicon.ico"))
                        {
                            // Skip further execution of current iteration
                            continue;
                        };
                        // Get command
                        char[] delimiter = {'?'};
                        string[] inputparts = context.Request.Url.ToString().Split(delimiter);
                        string command = inputparts[1];
                        // Get options
                        // Extract options after command
                        char[] optionsdelimiter = { ',' };
                        string[] options = inputparts[2].Split(optionsdelimiter);
                        string msg = "";
                        if (this.InvokeRequired)
                        {
                            this.Invoke(new EventHandler(delegate
                            {
                                msg = runCommandItem(command, options);
                            }));
                        }
                        else
                        {
                            runCommandItem(command, options);
                        }

                        // Define message and actions
                        context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(msg);
                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        // Add header to enable communication
                        context.Response.Headers.Add("Access-Control-Allow-Origin: *");
                        using (Stream stream = context.Response.OutputStream)
                        {
                            using (StreamWriter writer = new StreamWriter(stream))
                            {
                                writer.Write(msg);
                            }
                        }
                        // Return output to console (logTB)
                        saveLogText("Request answered: " + context.Request.Url.ToString());
                        saveLogText("Message sent...");
                        saveLogText("Action performed...");
                    }
                }
                catch (WebException ce)
                {
                    saveLogText(ce.Status.ToString());
                }
            }
            catch (Exception ex)
            {
                saveLogText(ex.ToString());
            }
        }

        public void saveLogText(string text)
        {
            // Run function outside thread
            if (this.InvokeRequired)
            {
                this.Invoke(new EventHandler(delegate
                {
                    logText(text);

                }));
            }
            else
            {
                logText(text + " - InvokeNotRequired");
            }
        }

        private void stopButton_Click(object sender, EventArgs e)
        {
            logText(stopServer());
        }

        // Run show
        presentation show = new presentation();
        private void openShowButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Hide controls
                show.mediaPlayer1.uiMode = "none";
                show.mediaPlayer2.uiMode = "none";
                show.backupMediaPlayer.uiMode = "none";
                // Set logo
                show.logoPlayer1.ImageLocation = vars.logoSource;
                show.Show();
            }
            catch (Exception ex)
            {
                logText(ex.ToString());
            }
        }

        // Controls
        public AxWMPLib.AxWindowsMediaPlayer[] allMediaPlayers()
        {
            AxWMPLib.AxWindowsMediaPlayer[] players = { show.mediaPlayer2, show.mediaPlayer1, show.backupMediaPlayer};
            return players;
        }
        public PictureBox[] allPhotoPlayers()
        {
            PictureBox[] players = {show.photoPlayer1, show.logoPlayer1 };
            return players;
        }
        public Panel[] allColorPlayers()
        {
            Panel[] players = { show.colorPlayer1 };
            return players;
        }

        public void hideAllPlayers(AxWMPLib.AxWindowsMediaPlayer exceptMP = null, PictureBox exceptPB = null, Panel exceptPanel = null)
        {
            // Hide all players in show
            AxWMPLib.AxWindowsMediaPlayer[] mediaPlayers = allMediaPlayers();
            foreach(AxWMPLib.AxWindowsMediaPlayer obj in mediaPlayers){
                if (obj != exceptMP)
                {
                    obj.Visible = false;
                }
            }            
            PictureBox[] photoPlayers = allPhotoPlayers();
            foreach (PictureBox obj in photoPlayers)
            {
                if (obj != exceptPB)
                {
                    obj.Visible = false;
                }
            }
            Panel[] colorPlayers = allColorPlayers();
            foreach (Panel obj in colorPlayers)
            {
                if (obj != exceptPanel)
                {
                    obj.Visible = false;
                }
            }
        }

        private void liveShowLogoButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Show logo
                runLogo();
            }
            catch
            {
                logText("Couldn't send command.");
            }
        }

        private void liveShowColorButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Show color
                ColorDialog cd = new ColorDialog();
                cd.ShowDialog();
                runColor(cd.Color);
            }
            catch
            {
                logText("Couldn't send command.");
            }
        }

        private void liveSetBlackButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Show black
                runColor(Color.Black);
            }
            catch
            {
                logText("Couldn't send command.");
            }
        }

        private void liveSetWhiteButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Show white
                runColor(Color.White);
            }
            catch
            {
                logText("Couldn't send command.");
            }

        }

        private void liveFullScreenButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Show full screen
                show.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                show.WindowState = FormWindowState.Maximized;
                logText("Full screen mode");
            }
            catch
            {
                logText("Couldn't send command.");
            }

        }

        private void liveMaximizeButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Show maximized
                show.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
                show.WindowState = FormWindowState.Maximized;
                logText("Maximized mode");
            }
            catch
            {
                logText("Couldn't send command.");
            }

        }

        private void liveWindowedButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Show windowed
                show.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
                show.WindowState = FormWindowState.Normal; ;
                logText("Windowed mode");
            }
            catch
            {
                logText("Couldn't send command.");
            }

        }

        private void liveMinimizeButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Show minimized
                show.WindowState = FormWindowState.Minimized;
                logText("Minimized mode");
            }
            catch
            {
                logText("Couldn't send command.");
            }

        }

        // Media control
        AxWMPLib.AxWindowsMediaPlayer bufferedPlayer;
        AxWMPLib.AxWindowsMediaPlayer currentMedia;
        // Proceed media
        public void proceedMedia()
        {
            try
            {
                vars.mediaStillHasToPlay = true;
                int gtsn = vars.goToScriptNumber;
                vars.goToScriptNumber = 0;
                runScriptItem(gtsn);
                saveLogText("proceedMedia success.");
            }
            catch
            {
                saveLogText("proceedMedia action failed.");
            }
        }
        // Show currently playing media control
        public void showCurrentMediaControl()
        {
            try
            {
                // Show video control if playing
                // Check if there's a video playing
                AxWMPLib.AxWindowsMediaPlayer[] mediaPlayers = allMediaPlayers();
                AxWMPLib.AxWindowsMediaPlayer videoPlayer = mediaPlayers[0];
                if (videoPlayer.playState == WMPLib.WMPPlayState.wmppsPlaying)
                {
                    videoPlayer.Visible = true; // Show video player
                    hideAllPlayers(videoPlayer);

                }
                else
                {
                    currentMedia.Visible = true; // Show music player (or probably other video players)
                    hideAllPlayers(currentMedia);

                }
                logText("Currently playing media control shown.");
            }
            catch
            {
                logText("Couldn't show currently playing media control");
            }
        }

        public void loadVideo(string source, Boolean play = true, Boolean mute = false, Boolean music = false, Boolean proceed = false, Int32 nextScriptNumber = 0)
        {// nextScriptNumber is only used when proceed = true
            try
            {
                // Check if there's a video playing
                AxWMPLib.AxWindowsMediaPlayer[] mediaPlayers = allMediaPlayers();
                AxWMPLib.AxWindowsMediaPlayer currentPlayer = mediaPlayers[0];

                // Check if this is music, if music use mediaplayer2
                if (music == true)
                {
                    currentPlayer = mediaPlayers[1]; // Music
                }
                else
                {
                    currentPlayer = mediaPlayers[0]; // Video
                }
                if (vars.mediaStillHasToPlay == true && bufferedPlayer != mediaPlayers[2])
                {
                    currentPlayer = mediaPlayers[2]; // Backup player
                    vars.mediaStillHasToPlay = false;
                }
                currentPlayer.settings.autoStart = false;

                currentPlayer.URL = source;
                currentPlayer.settings.mute = mute;
                bufferedPlayer = currentPlayer;
                logText("Video loaded, with mute:" + mute.ToString() + ", play:" + play.ToString());
                if (play == true)
                {
                    // Immediately run video
                    runVideo(bufferedPlayer, music);
                }
                if (proceed == true && nextScriptNumber != 0)
                {
                    // Set goToScriptNumber to nextScriptNumber
                    vars.goToScriptNumber = nextScriptNumber;
                }
            }
            catch
            {
                logText("Couldn't load video.");
            }
        }
        public void runVideo(AxWMPLib.AxWindowsMediaPlayer videoPlayer, Boolean music = false)
        {
            try
            {
                // Set videoplayer for previous control
                currentMedia = videoPlayer;

                // Stop all currently playing media
                //pauseMedia();
                if (music == false)
                {
                    videoPlayer.Visible = true;
                    hideAllPlayers(videoPlayer);

                }

                videoPlayer.Ctlcontrols.play();
                logText("Video playing");
                videoPlayer.stretchToFit = true;
            }
            catch
            {
                logText("Couldn't run video.");
            }
        }
        public void runPhoto(string source)
        {
            try
            {
                // Loop through all photoPlayers
                PictureBox[] photoPlayers = allPhotoPlayers();
                PictureBox currentPlayer = photoPlayers[0]; // For now, always use currentPlayer
                //TODO: switch between players to give the system some time to load the images

                
                currentPlayer.ImageLocation = source;
                currentPlayer.Visible = true;
                hideAllPlayers(null, currentPlayer);
                logText("Photo displayed");
            }
            catch (Exception ex)
            {
                logText("Error in runPhoto.");
            }
        }
        public void runColor(Color color)
        {
            try
            {
                Panel[] currentPlayers = allColorPlayers();
                Panel currentPlayer = currentPlayers[0]; // Use this player for displaying colors
                //TODO: make it easy to switch between colors
                currentPlayer.BackColor = color;
                currentPlayer.Visible = true;
                hideAllPlayers(null,null,currentPlayer);
                logText("Color {" + color.ToString() + "} is set.");
            }
            catch (Exception ex)
            {
                logText("Error in runColor.");
            }
        }
        public void runLogo()
        {
            try
            {
                show.logoPlayer1.Visible = true;
                hideAllPlayers(null,show.logoPlayer1);
                logText("Logo displayed");
            }
            catch (Exception ex)
            {
                logText("Error in runLogo.");
            }
        }
        public void pauseMedia()
        {
            try {
                AxWMPLib.AxWindowsMediaPlayer[] mediaPlayers = allMediaPlayers();
                foreach (AxWMPLib.AxWindowsMediaPlayer obj in mediaPlayers)
                {
                    obj.Ctlcontrols.pause();
                }
                logText("Media paused");
            }
            catch
            {
                logText("Couldn't pause media");
            }

        }
        public void stopMedia()
        {
            try {
                AxWMPLib.AxWindowsMediaPlayer[] mediaPlayers = allMediaPlayers();
                foreach (AxWMPLib.AxWindowsMediaPlayer obj in mediaPlayers)
                {
                    obj.Ctlcontrols.stop();
                }
                logText("Media stopped");
            }
            catch
            {
                logText("Couldn't stop media");
            }
        }

        private void liveShowVideoButton_Click(object sender, EventArgs e)
        {
            loadVideo(liveVideoSourceTextBox.Text, true);
            liveVideoSourceTextBox.Text = "";
        }

        private void liveLoadVideoButton_Click(object sender, EventArgs e)
        {
            loadVideo(liveVideoSourceTextBox.Text, false);
            liveVideoSourceTextBox.Text = "";
        }

        private void livePlayLoadedVideoButton_Click(object sender, EventArgs e)
        {
            runVideo(bufferedPlayer);
        }

        private void liveStopAllMediaButton_Click(object sender, EventArgs e)
        {
            stopMedia();
        }

        private void liveShowPlayingMediaButton_Click(object sender, EventArgs e)
        {
            showCurrentMediaControl();
        }

        private void liveShowImageButton_Click(object sender, EventArgs e)
        {
            runPhoto(liveImageSourceTextBox.Text);
            liveImageSourceTextBox.Items.Add(liveImageSourceTextBox.Text);
            liveImageSourceTextBox.Text = "";
        }

        private void liveShowMusicButton_Click(object sender, EventArgs e)
        {
            loadVideo(liveMusicSourceTextBox.Text, true, false, true);
            liveMusicSourceTextBox.Text = "";
        }

        private void livePlayLoadedMusicButton_Click(object sender, EventArgs e)
        {
            runVideo(bufferedPlayer, true);
        }

        private void liveLoadMusicButton_Click(object sender, EventArgs e)
        {
            loadVideo(liveMusicSourceTextBox.Text, false);
            liveMusicSourceTextBox.Text = "";

        }

        // Script
        List<scriptItem> scriptElements = new List<scriptItem>();
        int currentScriptID = -1;
        public void loadScript()
        {
            try
            {
                // Read the script file
                string line;
                List<string> scriptLines = new List<string>();
                System.IO.StreamReader file = new System.IO.StreamReader(Directory.GetParent(Application.ExecutablePath).ToString() + vars.scriptSource);
                while ((line = file.ReadLine()) != null)
                {
                    if (line.StartsWith("#"))
                    {
                        // Don't read lines starting with #
                    }
                    else
                    {
                        scriptLines.Add(line);
                    }
                }
                file.Close();
                // Loop through script elements to interpret
                foreach (string scriptLine in scriptLines){
                    char[] delimiter = {'?'};
                    string[] scriptLineElements = scriptLine.Split(delimiter);
                    
                    scriptItem si = new scriptItem();
                    // Extract command
                    si.command = scriptLineElements[0]; // First element before delimiter is command
                    // Add command to listbox
                    liveScriptListBox.Items.Add(scriptElements.Count() + " : " + si.command + " - " + scriptLineElements[1]);
                    // Extract options after command
                    char[] optionsdelimiter = {','};
                    si.options = scriptLineElements[1].Split(optionsdelimiter);
                    scriptElements.Add(si);
                }

                logText("Script loaded...");
            }
            catch (Exception ex)
            {
                logText(ex.ToString());
            }

        }

        public void startScript()
        {
            try
            {
                runScriptItem(0);
                logText("startScript");
            }
            catch
            {
                logText("Couldn't run startScript.");
            }
        }
        public void nextScript()
        {
            try
            {
                runScriptItem(currentScriptID + 1);
                logText("Next script item loaded");
            }
            catch
            {
                logText("Couldn't run next script item");
            }
        }
        public void previousScript()
        {
            try
            {
                runScriptItem(currentScriptID - 1);
                logText("Previous script item loaded");
            }
            catch
            {
                logText("Couldn't run previous script item");
            }
        }

        public void runScriptItem(int ScriptElementID)
        {
            try
            {
                scriptItem si = scriptElements[ScriptElementID];
                currentScriptID = ScriptElementID;
                liveCurrentScriptItemIDLabel.Text = ScriptElementID.ToString();
                runCommandItem(si.command, si.options);
            }
            catch
            {
                logText("Couldn't start script");
            }


        }
        public string runCommandItem(string command, string[] options)
        {
            try
            {
                switch (command)
                {
                    #region runVideo;
                    case "runVideo":
                        {
                            // runVideo options
                            string source = options[0];
                            Boolean autostart = false;
                            Boolean mute = false;
                            Boolean proceed = false;
                            // If proceed is set, get script number
                            Boolean getScriptNumber = false;
                            Int32 scriptNumber = 0;
                            // Set runVideo options
                            foreach (string option in options)
                            {
                                // Get scriptNumber if getScriptNumber=true
                                if (getScriptNumber == true)
                                {
                                    try
                                    {
                                        scriptNumber = Convert.ToInt32(option);
                                        saveLogText("Got script number for proceed.");
                                        getScriptNumber = false;
                                    }
                                    catch
                                    {
                                        saveLogText("Couldn't get script number for proceed.");
                                    }
                                }
                                switch (option)
                                {
                                    case "autostart":
                                        {
                                            autostart = true;
                                            break;
                                        }
                                    case "mute":
                                        {
                                            mute = true;
                                            break;
                                        }
                                    case "proceed":
                                        {
                                            proceed = true;
                                            getScriptNumber = true; // Get script number right behind proceed
                                            // We also need to get a script number that we have to run next
                                            break;
                                        }
                                }
                                
                            }
                            loadVideo(source, autostart, mute, false, proceed, scriptNumber);
                            break;
                        }
                    #endregion
                    #region runMusic;
                    case "runMusic":
                        {
                            // runMusic options
                            string source = options[0];
                            Boolean autostart = false;
                            Boolean mute = false;
                            Boolean proceed = false;
                            // If proceed is set, get script number
                            Boolean getScriptNumber = false;
                            Int32 scriptNumber = 0;
                            // Set runVideo options
                            foreach (string option in options)
                            {
                                // Get scriptNumber if getScriptNumber=true
                                if (getScriptNumber == true)
                                {
                                    try
                                    {
                                        scriptNumber = Convert.ToInt32(option);
                                        saveLogText("Got script number for proceed.");
                                        getScriptNumber = false;
                                    }
                                    catch
                                    {
                                        saveLogText("Couldn't get script number for proceed.");
                                    }
                                }
                                switch (option)
                                {
                                    case "autostart":
                                        {
                                            autostart = true;
                                            break;
                                        }
                                    case "mute":
                                        {
                                            mute = true;
                                            break;
                                        }
                                    case "proceed":
                                        {
                                            proceed = true;
                                            getScriptNumber = true; // Get script number right behind proceed
                                            // We also need to get a script number that we have to run next
                                            break;
                                        }
                                }
                            }
                            loadVideo(source, autostart, mute, true, proceed, scriptNumber);
                            break;
                        }
                    #endregion
                    #region runCachedVideo;
                    case "runCachedVideo":
                        {
                            runVideo(bufferedPlayer);
                            break;
                        }
                    #endregion
                    #region runCachedMusic;
                    case "runCachedMusic":
                        {
                            runVideo(bufferedPlayer, true);
                            break;
                        }
                    #endregion
                    #region runLogo;
                    case "runLogo":
                        {
                            // runLogo options
                            runLogo();
                            break;
                        }
                    #endregion
                    #region runPhoto;
                    case "runPhoto":
                        {
                            // runPhoto options
                            string source = options[0];
                            runPhoto(source);
                            break;
                        }
                    #endregion
                    #region runColor;
                    case "runColor":
                        {
                            // runColor options
                            int r = Convert.ToInt16(options[0]);
                            int g = Convert.ToInt16(options[1]);
                            int b = Convert.ToInt16(options[2]);
                            Color rgbcolor = new Color();
                            rgbcolor = Color.FromArgb(255, r, g, b);
                            runColor(rgbcolor);
                            break;
                        }
                    #endregion
                    #region runBlack;
                    case "runBlack":
                        {
                            runColor(Color.Black);
                            break;
                        }
                    #endregion
                    #region runWhite;
                    case "runWhite":
                        {
                            runColor(Color.White);
                            break;
                        }
                    #endregion
                    #region windowFullScreen;
                    case "windowFullScreen":
                        {
                            // Show full screen
                            show.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                            show.WindowState = FormWindowState.Maximized;
                            logText("Full screen mode");
                            break;
                        }
                    #endregion
                    #region windowMaximize;
                    case "windowMaximize":
                        {
                            // Show maximized
                            show.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
                            show.WindowState = FormWindowState.Maximized;
                            logText("Maximized mode");
                            break;
                        }
                    #endregion
                    #region windowMinimize;
                    case "windowMinimize":
                        {
                            // Show minimized
                            show.WindowState = FormWindowState.Minimized;
                            logText("Minimized mode");
                            break;
                        }
                    #endregion
                    #region windowWindowed;
                    case "windowWindowed":
                        {
                            // Show windowed
                            show.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
                            show.WindowState = FormWindowState.Normal; ;
                            logText("Windowed mode");
                            break;
                        }
                    #endregion
                    #region stopMedia;
                    case "stopMedia":
                        {
                            stopMedia();
                            break;
                        }
                    #endregion
                    #region pauseMedia;
                    case "pauseMedia":
                        {
                            pauseMedia();
                            break;
                        }
                    #endregion
                    #region reloadScript;
                    case "reloadScript":
                        {
                            liveScriptListBox.Items.Clear();
                            scriptElements.Clear();
                            loadScript();
                            break;
                        }
                    #endregion
                    #region scriptNext;
                    case "scriptNext":
                        {
                            nextScript();
                            break;
                        }
                    #endregion
                    #region scriptPrevious;
                    case "scriptPrevious":
                        {
                            previousScript();
                            break;
                        }
                    #endregion
                    #region scriptStart;
                    case "scriptStart":
                        {
                            runScriptItem(0);
                            break;
                        }
                    #endregion
                    #region scriptID;
                    case "scriptID":
                        {
                            runScriptItem(Convert.ToInt32(options[0]));
                            break;
                        }
                    #endregion
                    #region emptyLog;
                    case "emptyLog":
                        {
                            logTB.Text = "";
                            break;
                        }
                    #endregion
                    #region getScriptHTML;
                    case "getScriptHTML":
                        {
                            string html = "<table>";
                            int count = 0;
                            foreach (scriptItem item in scriptElements)
                            {
                                string optionsString = "";
                                int i = 0;
                                foreach (string option in item.options)
                                {
                                    if (i == 0)
                                    {
                                        optionsString += option;
                                    }
                                    else
                                    {
                                        optionsString += ", " + option;
                                    }
                                    i++;
                                }
                                html += "<tr onclick='executeCommand(\"scriptID\", \"" + count + "\")'><td>" + count + "</td><td>" + item.command + "</td><td> " + optionsString + "</td></tr>";
                                count++;
                            }
                            html += "</table>";
                            return html;
                            break;
                        }
                    #endregion
                    #region currentMedia;
                    case "currentMedia":
                        {
                            showCurrentMediaControl();
                            break;
                        }
                    #endregion
                    #region returnCurrentScriptID;
                    case "returnCurrentScriptID":
                        {
                            return currentScriptID.ToString();
                            break;
                        }
                    #endregion
                    #region reloadChat;
                    case "reloadChat":
                        {
                            string addContent = "";
                            int i = 0;
                            foreach (string option in options)
                            {
                                if (i != 0)
                                {
                                    addContent += "," + option;
                                }
                                else
                                {
                                    addContent += option;
                                }
                                i++;
                            }
                            if (addContent != "")
                            {
                                vars.chatContent = addContent + vars.chatContent;
                            }
                            saveLogText("Chat updated...");
                            return vars.chatContent;
                            break;
                        }
                    #endregion
                    #region play;
                    case "play":
                        {
                            try
                            {
                                AxWMPLib.AxWindowsMediaPlayer mplayer = new AxWMPLib.AxWindowsMediaPlayer();
                                AxWMPLib.AxWindowsMediaPlayer[] allplayers = allMediaPlayers();
                                foreach (string option in options)
                                {
                                    if (option == "video")
                                    {
                                        mplayer = allplayers[0];
                                    }
                                    else
                                    {
                                        mplayer = allplayers[1];
                                    }
                                }
                                if (allplayers[2].playState == WMPLib.WMPPlayState.wmppsPaused) // backup player paused
                                {
                                    mplayer = allplayers[2];
                                }
                                mplayer.Ctlcontrols.play();
                                saveLogText("Playing...");

                            }
                            catch
                            {
                                saveLogText("Error play.");
                            }
                            break;
                        }
                    #endregion
                    #region pause;
                    case "pause":
                        {
                            try
                            {
                                AxWMPLib.AxWindowsMediaPlayer mplayer = new AxWMPLib.AxWindowsMediaPlayer();
                                AxWMPLib.AxWindowsMediaPlayer[] allplayers = allMediaPlayers();
                                foreach (string option in options)
                                {
                                    if (option == "video")
                                    {
                                        mplayer = allplayers[0];
                                    }
                                    else
                                    {
                                        mplayer = allplayers[1];
                                    }
                                }
                                if (allplayers[2].playState == WMPLib.WMPPlayState.wmppsPlaying) // backup player paused
                                {
                                    mplayer = allplayers[2];
                                }
                                mplayer.Ctlcontrols.pause();
                                saveLogText("Paused...");

                            }
                            catch
                            {
                                saveLogText("Error pause.");
                            }
                            break;
                        }
                    #endregion

                }

            }
            catch
            {
                saveLogText("Error runCommandItem");
            }
            return (logTB.Text);
        }

        private void liveScriptStartButton_Click(object sender, EventArgs e)
        {
            startScript();
        }

        private void liveScriptNextButton_Click(object sender, EventArgs e)
        {
            nextScript();
        }

        private void liveScriptPreviousButton_Click(object sender, EventArgs e)
        {
            previousScript();
        }

        private void liveScriptListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                runScriptItem(liveScriptListBox.SelectedIndex);
            }
            catch
            {
                logText("Failed to hop to selected script item");
            }
        }

        private void liveScriptReloadButton_Click(object sender, EventArgs e)
        {
            liveScriptListBox.Items.Clear();
            scriptElements.Clear();
            loadScript();
        }

        private void scriptBuilderButton_Click(object sender, EventArgs e)
        {
            scriptBuilder sb = new scriptBuilder();
            sb.Show();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            stopServer();
        }

        private void chatButton_Click(object sender, EventArgs e)
        {
            chat ch = new chat();
            ch.Show();
        }

        private void playVideoButton_Click(object sender, EventArgs e)
        {
            string[] options = {"video"};
            runCommandItem("play", options);
        }

        private void pauseVideoButton_Click(object sender, EventArgs e)
        {
            string[] options = { "video" };
            runCommandItem("pause", options);
        }

        private void pauseMusicButton_Click(object sender, EventArgs e)
        {
            string[] options = { "music" };
            runCommandItem("pause", options);
        }

        private void playMusicButton_Click(object sender, EventArgs e)
        {
            string[] options = { "music" };
            runCommandItem("play", options);
        }
    }
}
